package com.tracking.locon;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.ListView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class Track extends MapActivity implements LocationListener{
	
	private static final float METER_SCAN = 500;
	private static final int DEFAULT_ZOOM = 17;
	private MyLocationOverlay mCompass;
	private LocationManager mLocationManager;
	
	private MapView mMapView;
	//private GoogleMap mGMap;
	private Context mContext;
	//private ListView mNearbyList;
	//private String[] mNearbyArray;
	
	protected class LocationData{
		GeoPoint geoPoint;
		int latitude;
		int longitude;
	}
	
	public Track() {
		
	}
	/*
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.track, container, false);
        setupTrack(view);
        return view;
    }
	
	private void setupTrack(View view){
		mMapView = (MapView) view.findViewById(R.id.mvTrack);
		//mGMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.mvTrack)).getMap();
		mContext = getActivity();
		setMapRules(mMapView);
		setLocation();
		setCompass(mMapView);
		//setNearbyList();
	}
	*/
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.track);
		
		mMapView = (MapView) findViewById(R.id.mvTrack);
		mContext = this;
		setMapRules(mMapView);
		
		setLocation();
		setCompass(mMapView);
		TrackNearbyList list = new TrackNearbyList();
		list.setupNearbyList();
		//searchNearbyFriend();
	}
	
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	@Override
	public void onPause(){
		mCompass.disableCompass();
		mLocationManager.removeUpdates(this);
		super.onPause();
	}
	
	@Override
	public void onResume(){
		mCompass.enableCompass();
		setLocation();
		super.onResume();
	}
	
	/*
	private void setNearbyList(){
		TrackListFragment trackFrag = (TrackListFragment) getFragmentManager()
                .findFragmentById(R.id.fFriendNearby);
		if (trackFrag == null) {
			//Start Fragment TrackList
			Intent intent = new Intent(this, TrackListFragment.class);
			startActivity(intent);
		} else {
			//do something
		}
	}
	*/
	
	/* TODO Set the Map Rules */
	private void setMapRules(MapView mapView) {
		mapView.getController().setZoom(DEFAULT_ZOOM);
	}
	
	/*
	 * Set compass in the map
	 */
	private void setCompass(MapView mapView){
		mCompass = new MyLocationOverlay(mContext, mapView);
		List<Overlay> overlayList = mapView.getOverlays();
		overlayList.add(mCompass);
	}
	
	private void setLocation() {
		//Use Location Service
		Log.d("TAG","1");
		mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
		Log.d("TAG","2");
		String locationProvider = getBestProvider(mLocationManager);
		Log.d("TAG","3");
		mLocationManager.requestLocationUpdates(locationProvider, 0, 0, this);
	}
	
	/*
	 * Get the best location provider
	 */
	private String getBestProvider(LocationManager locationManager){
		//Criteria criteria = new Criteria();
		String locationProvider = LocationManager.NETWORK_PROVIDER;
		//String locationProvider = locationManager.getBestProvider(criteria, false);
		return locationProvider;
	}
	
	/*
	 * Extract Latitude and Longitude from Location data
	 * @return = Object containing latitude, longitude, and geopoint
	 */
	private LocationData extractLocationData(Location location){
		LocationData data = new LocationData();
			data.latitude = (int) (location.getLatitude() * 1e6);
			data.longitude = (int) (location.getLongitude() * 1e6);
			data.geoPoint = new GeoPoint(data.latitude, data.longitude);
		
		return data;
	}
	
	public void onLocationChanged(Location location) {
		LocationData data = extractLocationData(location);
		//Utility.makeToast(this, "New location");
		//Log.d(TAG, String.format("Latitude %s, Longitude %s", data.latitude, data.longitude));
		addOverlay(data);
	}
	
	/*
	 * Add pin and blue circle in the map
	 */
	private void addOverlay(LocationData data){
		List<Overlay> mapOverlays = mMapView.getOverlays();
		//Delete all overlay except the compass before updating
		for(int i = mapOverlays.size(); mapOverlays.size() > 1; i--){
			mapOverlays.remove(i-1);
		}
		
		mMapView.getController().animateTo(data.geoPoint);
		
		//Utility.makeToast(this, String.format("Latitude %s Longitude %s", data.latitude, data.longitude));
		
		mapOverlays.add(drawCircleRadius(data.geoPoint, METER_SCAN));
		mapOverlays.add(drawPin(data.geoPoint, "Your Location"));
	}
	
	
	/*
	 * Draw blue circle surrounding the pin
	 * @return The circle overlay
	 */
	protected TrackCircleOverlay drawCircleRadius(GeoPoint geoPoint, float meter){
		TrackCircleOverlay circleOverlay = new TrackCircleOverlay(mContext, geoPoint, meter);
		return circleOverlay;
	}
	
	/*
	 * Draw pin marker on the map
	 * @return The pin overlay
	 */
	protected TrackItemizedOverlay drawPin(GeoPoint geoPoint, String name){
		//Choose the image and set it
		Drawable drawable_pin = this.getResources().getDrawable(R.drawable.circle_pin);
		TrackItemizedOverlay itemizedOverlay = new TrackItemizedOverlay(drawable_pin, mContext);
		
		//Set the location to put the image
		OverlayItem overlayItem = new OverlayItem(geoPoint, name, "");
		itemizedOverlay.addOverlay(overlayItem);
		return itemizedOverlay;
	}
	
	public void onProviderDisabled(String provider) {
		RequestTurnOnLocationService();
	}
	
	/*
	 * Dialog asking to turn on Location Service
	 */
	private void RequestTurnOnLocationService(){
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(R.string.location_dialogWhenOffTitle)
				.setMessage(R.string.location_dialogWhenOffBody)
				.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
						startActivity(i);
					}
				})
				.setNegativeButton(R.string.NO, new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
	}
	
	public class TrackNearbyList{
		private ListView mNearbyListView;
		private String[] mNearbyData;
		
		private void setupNearbyList(){
			mNearbyListView = (ListView) findViewById(R.id.lvFriendNearby);
			mNearbyData = getTrackData();
	        setTrackListView(mNearbyListView, mNearbyData);
		}
		
		private void setTrackListView(ListView listView, String[] trackData){
			ContactOne[] trackList = new ContactOne[trackData.length];
	        for(int i = 0; i < trackData.length; i++){
	        	trackList[i] = new ContactOne(R.drawable.icon_person, trackData[i], 
	        			Math.round(Math.random()*500)+"m");
	        }
	        ContactAdapter adapter = new ContactAdapter(mContext, R.layout.contact_row, trackList);
	        
	        listView.setAdapter(adapter);
		}
		
		private String[] getTrackData(){
			return getResources().getStringArray(R.array.arrayTestTrack);
		}
	}// TrackNearbyList
}// class
